package com.corpgovernment.common.utils.JsonDeserializerUtils;

import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;

import java.io.IOException;
import java.util.List;

public class EmptyListToEmptyString extends JsonDeserializer {

    /**
     * 针对于供应商接口字段空数据返回值是个[]数组实际有值时候是String类型。
     * {"str": -1} -> "-1" | {"str": []} -> "" |  {"str": ["1","2"]} -> "["1","2"]" | {"str": true} -> "true"
     * @param jsonParser
     * @return
     * @throws IOException
     */
    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String data = "";
        switch (jsonParser.getCurrentToken().name()) {
            case "START_ARRAY":
                List list = jsonParser.readValueAs(List.class);
                if (!CollectionUtils.isEmpty(list) && list.size() > 0){
                    data = JsonUtils.toJsonString(list);
                }
                break;
            //case "VALUE_STRING":
            //    data = jsonParser.getText();
            //    break;
            default:
                data = jsonParser.getText();
                break;
        }
        return data;
    }
}
